//
//  YPDiscoverViewController.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/1/9.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "YPDiscoverViewController.h"
#import "YPActivityCenterViewController.h"
#import "YPMemberCenterViewController.h"
#import "YPNoticeViewController.h"
#import "YPDynamicViewController.h"
#import "RxWebViewController.h"
#import "UIImage+GIF.h"

@interface YPDiscoverViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>{
    
    NSArray *_dataArray;
}

@property (nonatomic,strong)UICollectionView *collectionView;

@end

@implementation YPDiscoverViewController

#pragma mark -- lazzy
- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
   
        UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc]init];
        flowLayOut.minimumLineSpacing = autoScaleW(15);
        flowLayOut.minimumInteritemSpacing = flowLayOut.minimumLineSpacing;
        flowLayOut.itemSize = CGSizeMake((SCREEN_WIDTH - flowLayOut.minimumInteritemSpacing * 3 - 2)/2.f, 70);
        flowLayOut.sectionInset = UIEdgeInsetsMake(autoScaleW(15), autoScaleW(15), autoScaleW(15), autoScaleW(15));
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) collectionViewLayout:flowLayOut];
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        MJRefreshGifHeader *gifHeader = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            
            [self requestData];
        }];
        
        [gifHeader.lastUpdatedTimeLabel setValue:@(YES) forKey:@"hidden"];
        [gifHeader.stateLabel setValue:@(YES) forKey:@"hidden"];
        
        
        UIImage *imagegif = [UIImage sd_animatedGIFNamed:@"jixiangwu"];
        
        NSArray *imagesArr = imagegif.images;
        // 设置普通状态的动画图片
        [gifHeader setImages:imagesArr forState:MJRefreshStateIdle];
        // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
        [gifHeader setImages:imagesArr forState:MJRefreshStatePulling];
        // 设置正在刷新状态的动画图片
        [gifHeader setImages:imagesArr forState:MJRefreshStateRefreshing];
        
        _collectionView.header = gifHeader;
        
    }
    
    return _collectionView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self.view addSubview:self.collectionView];
    
    if (_dataArray.count == 0) {
        [self.collectionView.header beginRefreshing];
    }
    
}

- (void)requestData{
    
    [YPHttpRequestMethod sendAsyRequestURL:YPDisCover_URL withData:nil withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        if ([responseDictionary[@"status"] integerValue] == 0) {
            
            _dataArray = responseDictionary[@"list"];
            
            [self.collectionView reloadData];
            
        }
        [self.collectionView.header endRefreshing];
        
    } withFailedBlock:^(NSError *error) {
        
        [self.collectionView.header endRefreshing];
        
    } withIndicator:NO atView:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return [_dataArray count];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    /*
     name:名称
     description:描述
     icon_url:图片地址
     link_url:链接地址
     need_token:是否需要token(0不需要，1需要)
     */
    NSDictionary *dataDic = _dataArray[indexPath.row];
    
    
    UILabel *titleLabel= [cell.contentView viewWithTag:100];
    if (!titleLabel) {
        
        titleLabel = [UILabel creatWithFrame:CGRectMake(10, 15, 100, 20)
                                        font:[UIFont systemFontOfSize:17]
                                        text:@""
                                   textColor:[UIColor blackColor]
                               textAlignment:0];
        titleLabel.tag = 100;
        [cell.contentView addSubview:titleLabel];
    }
    
    
    UILabel *subLabel= [cell.contentView viewWithTag:101];
    if (!subLabel) {
        
        subLabel = [UILabel creatWithFrame:CGRectMake(titleLabel.left, titleLabel.bottom, titleLabel.width, titleLabel.height)
                                        font:[UIFont systemFontOfSize:11]
                                        text:@""
                                   textColor:kColor_greyAshTitleColor
                               textAlignment:0];
        subLabel.tag = 101;
        [cell.contentView addSubview:subLabel];
    }
    
    UIImageView *imageView = [cell.contentView viewWithTag:102];
    if (!imageView) {
        
        imageView = [[UIImageView alloc]initWithFrame:CGRectMake(cell.width - autoScaleW(45) - 10, (cell.height - autoScaleW(45))/2.f, autoScaleW(45), autoScaleW(45))];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        imageView.tag = 102;
        [cell.contentView addSubview:imageView];
    }

    cell.contentView.backgroundColor = colorWithRGB(247, 248, 249);
    cell.contentView.layer.cornerRadius = 5.f;
    cell.contentView.layer.masksToBounds = YES;
    
    
    titleLabel.text = dataDic[@"name"];
    subLabel.text = dataDic[@"description"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:dataDic[@"icon_url"]]];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSDictionary *dic = _dataArray[indexPath.row];
    NSString *baseUrl = dic[@"link_url"];
    if ([dic[@"need_token"] integerValue] == 1) { //需要token
        if (TOKEN) { //验证token有效性
            collectionView.allowsSelection = NO;
            [YPHttpRequestMethod sendAsyRequestURL:YPVerifyToken_URL withData:@{@"token":TOKEN} withCompletionBlock:^(NSDictionary *responseDictionary) {
                
                collectionView.allowsSelection = YES;
                if ([responseDictionary[@"status"] integerValue] == 0) {
                    [self goWebViewWithUrlString:[baseUrl stringByAppendingString:[NSString stringWithFormat:@"%@token=%@",[baseUrl rangeOfString:@"?"].location == NSNotFound?@"?":@"&",TOKEN]]];
                   
                }else{
                    [self goToLoginVCWithCompleteBlock:^(NSString *token){
                        
                        [self goWebViewWithUrlString:[baseUrl stringByAppendingString:[NSString stringWithFormat:@"%@token=%@",[baseUrl rangeOfString:@"?"].location == NSNotFound?@"?":@"&",TOKEN]]];
                    }];
                }
            } withFailedBlock:^(NSError *error) {
                collectionView.allowsSelection = YES;
            } withIndicator:NO atView:nil];
            
        }else{ //没有token
            
            [self goToLoginVCWithCompleteBlock:^(NSString *token){
                
                [self goWebViewWithUrlString:[baseUrl stringByAppendingString:[NSString stringWithFormat:@"%@token=%@",[baseUrl rangeOfString:@"?"].location == NSNotFound?@"?":@"&",TOKEN]]];
            }];
        }

    }else{
        
        [self goWebViewWithUrlString:baseUrl];
    }
    

}

- (void)goWebViewWithUrlString:(NSString *)urlString{

    YPGoWebView(urlString, self.navigationController);
}

@end
